package com.lemon.smartsafetynew.ui.fragment.user.forgetpassword;

import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.AesEncryptor;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafetynew.entity.event.user.PageEvent;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/7/18.
 */

public class UserForgetPasswordStepTwoFragment extends BaseFragment {

    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.eye_imageView)
    ImageView eyeImageView;
    @Bind(R.id.password_error_info_tv)
    TextView passwordErrorInfoTv;
    @Bind(R.id.retype_password_edit)
    EditText retypePasswordEdit;
    @Bind(R.id.retype_password_error_info_tv)
    TextView retypePasswordErrorInfoTv;


    private MaterialDialog materialDialog;

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_forget_password_step_two;
    }

    @Override
    protected void initViews() {

        passwordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                passwordErrorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        retypePasswordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                retypePasswordErrorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.next_btn, R.id.eye_imageView})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.next_btn:

                String password = passwordEdit.getText().toString().trim();
                String retypePassword = retypePasswordEdit.getText().toString().trim();
                if (checkPassword(password) && matcherPassword(password)) {

                    if (checkRetypePassword(retypePassword) && equalRetypePassword(password, retypePassword)) {

                        String telephoneNum = AppSharePreferenceUtil.getInstance().getString(SafeCloudConstants.USER_TELEPHONE_NUMBER, "");

                        AccountServices.init().forgetPasswordResetPassword(telephoneNum, AesEncryptor.encrypt(password));

                    } else {
                        retypePasswordErrorInfoTv.setText(getString(R.string.retype_password_error));
                    }

                } else {
                    passwordErrorInfoTv.setText(getString(R.string.password_format_error));
                }

                break;
            case R.id.eye_imageView:

                eyeImageView.setSelected(!eyeImageView.isSelected());
                if (eyeImageView.isSelected()) {
                    passwordEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    passwordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
        }

    }

    private boolean checkPassword(String password) {
        return !(null == password || "".equals(password));
    }

    private boolean matcherPassword(String password) {

        String pattern = "^[A-Za-z0-9]{6,25}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(password);

        return mMatcher.matches();
    }

    private boolean checkRetypePassword(String retypePassword) {
        return !(null == retypePassword || "".equals(retypePassword));
    }

    private boolean equalRetypePassword(String password, String retypePassword) {
        return password.equals(retypePassword);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent<String> event) {

        if (KeyConstants.URL_FORGET_PASSWORD_RESET_PASSWORD.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    Toast.makeText(getmContext(), "修改密码成功", Toast.LENGTH_LONG).show();
                    AppService.getBus().post(new PageEvent());

                } else {
                    Toast.makeText(getmContext(), event.getObj(), Toast.LENGTH_LONG).show();
                }
            }
        }

    }

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(getActivity())
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }
}
